﻿using Coldairarrow.Entity;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using NetTopologySuite.Index.HPRtree;
using NetTopologySuite.Index.Sweepline;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_Manage
{
    public class Base_InterfaceOptionBusiness : BaseBusiness<Base_InterfaceOption>, IBase_InterfaceOptionBusiness, ITransientDependency
    {
        public Base_InterfaceOptionBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<Base_InterfaceOption>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_InterfaceOption>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_InterfaceOption, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_InterfaceOption> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Base_InterfaceOption data)
        {
            await InsertAsync(data);
        }


        /// <summary>
        /// 复制新增
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional(IsolationLevel.ReadCommitted)]
        public async Task CopyDataAsync(CopyInterfaceDTO data)
        {
            data.Name = $"{data.Name}_Copy";
            await InsertAsync(data);
            string oldId = data.OldId;
            //获取所有旧数据
            List<Base_InterfaceOptionEntry> entry = Db.GetIQueryable<Base_InterfaceOptionEntry>().Where(i => i.OptionId == oldId).ToList();
            //获取旧数据的最高级父项
            List<Base_InterfaceOptionEntry> parNodes = entry.Where(x => x.ParentId.IsNullOrEmpty()).ToList();
            foreach (var item in entry)
            {
                //循环新增子项
                item.Id = IdHelper.GetId();
                item.OptionId = data.Id;
                item.Notes = "Copy";
            };
            SetParent<Base_InterfaceOptionEntry>(entry, "NodeNO", "ParentNO", "ParentId", parNodes);
            await Db.InsertAsync<Base_InterfaceOptionEntry>(entry);


        }

        /// <summary>
        /// 设置新增的父项ID
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">数据列表</param>
        /// <param name="nodeField">节点字段的名称</param>
        /// <param name="parField">父节点字段的名称</param>
        /// <param name="parNodes">最高层级的父项</param>
        /// <returns></returns>
        private List<T> SetParent<T>(List<T> list, string nodeField, string parField, string parIdField, List<T> parNodes)
        {
            Type type = typeof(T);
            string Id = "";
            if (!type.GetProperty(nodeField).IsNullOrEmpty() || !type.GetProperty(parField).IsNullOrEmpty())
            {
                foreach (var item in parNodes)
                {
                    //查询父节点的子节点
                    List<T> chrNode = list.Where(x => !x.GetPropertyValue(parField).IsNullOrEmpty()).Where(x => item.GetPropertyValue(nodeField).ToString() == x.GetPropertyValue(parField).ToString()).ToList();
                    //如果存在继续递归获取下级子节点
                    if (chrNode.Count > 0)
                    {
                        SetParent<T>(list, nodeField, parField, parIdField, chrNode);
                    }
                    //如果父节点ID不为空，设置当前项的父项节点ID
                    if (!item.GetPropertyValue(parField).IsNullOrEmpty())
                    {
                        Id = list.Where(l => item.GetPropertyValue(parField).ToString() == l.GetPropertyValue(nodeField).ToString()).First().GetPropertyValue("Id").ToString();
                        item.SetPropertyValue(parIdField, Id);
                    }
                }
            }
            return list;
        }
        public async Task UpdateDataAsync(Base_InterfaceOption data)
        {
            await UpdateAsync(data);
        }
        List<string> entryId;

        [Transactional(IsolationLevel.ReadCommitted)]
        public async Task DeleteDataAsync(List<string> ids)
        {
            foreach (var item in ids)
            {
                List<Base_InterfaceOptionEntry> list = Db.GetIQueryable<Base_InterfaceOptionEntry>().Where(x => x.OptionId == item).ToList();
                List<Base_InterfaceOptionEntryL> list2 = Db.GetIQueryable<Base_InterfaceOptionEntryL>().Where(x => x.HId == item).ToList();
                //删除API字符串配置信息
                if (list.Count > 0)
                {
                    List<string> IdList = list.Select(x => x.Id).ToList();
                    entryId = list.Select(x => x.Id).ToList();
                    await Db.DeleteAsync<Base_InterfaceOptionEntry>(entryId);
                }
                //删除对应的字段映射信息
                if (list2.Count > 0)
                {
                    List<string> IdList = list2.Select(x => x.Id).ToList();
                    entryId = list2.Select(x => x.Id).ToList();
                    await Db.DeleteAsync<Base_InterfaceOptionEntry>(entryId);
                }
            }
            await DeleteAsync(ids);
        }

        #endregion

        public async Task<Base_ColumnStyle[]> GetColumnsAsync(string tabName)
        {
            return await GetColumnsBaseAsync(tabName);
        }

        #region 私有成员

        #endregion
    }
}